import {
  addHealthManageApi,
  deleteHealthManage,
  getHealthManageApi,
  getFamilyMemberApi,
  updateFamilyArchiveStatus,
  sendMsg,
  getPersonInfoApi,
  searchFamilyName
} from "../../../services/filing/filing"
import {
  GETSTORAGE
} from "../../../services/storage/storage"
import {
  getWechat
} from "../../../services/_utils/api"
Page({
  data: {
    listState: 0, //非空显示
    nameDialog: '', //弹出框内的名字
    showWarnConfirm: false, // 模态框falg
    familyMemberId: '',
    presentIndex: '',
    personalInfoId: '',
    btnFlag: true,
    promptPopup: false,
    userFamilyIds: ['111'],
    userPersonId: '',
    familyNames: [],
    allList: []
  },
  //获取用户个人信息
  getUserInfo() {
    const userId = GETSTORAGE('userId')
    getPersonInfoApi({
      userId: userId
    }).then(res => {
      console.log(res, "用户个人信息");
      const {
        familyIds,
        personId
      } = res.data.data
      this.setData({
        userFamilyIds: familyIds,
        userPersonId: personId
      })
      this.getInitData()
    })
  },

  // 获取信息
  getInitData() {
    const list = []
    const familyId = GETSTORAGE('familyId')
    // 所有家庭
    this.data.userFamilyIds.forEach(item => {
      // 请求家庭名字
      searchFamilyName({
        familyId: item
      }).then(res => {
        const name = res.data.data.familyName
        getHealthManageApi({
          familyId: item
        }).then(res => {
          const not = res.data.data.filter(ele => ele.healthManageId == null)
          const join = res.data.data.filter(ele => ele.healthManageId != null)
          let obj = {
            not: not,
            join: join,
            familyId: item,
            familyName: name
          }
          if (familyId == item) {
            list.unshift(obj)
          } else {
            list.push(obj)
          }
          this.setData({
            allList: list
          })
          console.log(this.data.allList);
          getFamilyMemberApi({
            familyId: item,
            familyMemberId: ''
          }).then(res => {
            // console.log(res, "家庭成员");
            this.data.allList.forEach((item, index) => {
              this.data.allList[index].not.forEach((ele, i) => {
                res.data.data.forEach((ee, rr) => {
                  if (ee.familyMemberId == ele.familyMemberId) {
                    this.data.allList[index].not[i] = ee
                    this.setData({
                      allList: this.data.allList
                    })
                  }
                })
              })

              this.data.allList[index].join.forEach((ele, i) => {
                res.data.data.forEach((ee, rr) => {
                  if (ee.familyMemberId == ele.familyMemberId) {
                    this.data.allList[index].join[i] = ee
                    this.setData({
                      allList: this.data.allList
                    })
                  }
                })
              })
            })
          })

        })
      })

    })
  },
  // 更新建档状态
  update() {
    const familyId = GETSTORAGE('familyId')
    updateFamilyArchiveStatus({
      familyId: familyId,
      status: "health_manage"
    }).then(res => {})
  },


  // 加入健康管理弹出框显示
  showDialog(e) {
    console.log(e);
    const {
      familymemberid,
      name,
      personalinfoid
    } = e.currentTarget.dataset;
    this.setData({
      showWarnConfirm: true,
      nameDialog: name,
      familyMemberId: familymemberid,
      personalInfoId: personalinfoid
    });
  },
  closePrompt() {
    this.setData({
      promptPopup: false
    })
  },
  closeDialog() {
    this.setData({
      showWarnConfirm: false
    });
  },
  // 加入健康管理
  changeJoin(e) {
    const userId = GETSTORAGE('userId')
    let obj = {
      userId: userId,
      familyMemberId: this.data.familyMemberId,
      requestedPermissions: []
    }
    console.log(obj);
    // 调用添加健康管理
    addHealthManageApi(obj).then(res => {
      console.log(res, "添加健康管理")
      if (res.data.data.healthManageId != null) {
        console.log('111');
        this.getInitData()
        this.closeDialog()
      } else {
        const healthManageConfirmRequestId = res.data.data.healthManageConfirmRequestId
        getWechat({
          familyMemberId: this.data.familyMemberId
        }).then(res => {
          console.log(res, "微信用户信息");
          this.closeDialog()
          if (res.data.data.serviceOfficialAccountOpenid == '' || res.data.data.serviceOfficialAccountOpenid == null) {
            this.setData({
              promptPopup: true
            })
          } else {
            sendMsg({
              requestId: healthManageConfirmRequestId,
              familyMemberId: this.data.familyMemberId
            }).then(res => {
              console.log(res, "模板消息");
              this.getInitData()
            })
          }
        })

      }
    })
  },
  // 取消健康管理
  cancelJoin(e) {
    console.log(e);
    const {
      familymemberid,
      familyid
    } = e.currentTarget.dataset
    // 获取健康管理关系
    getHealthManageApi({
      familyId: familyid
    }).then(res => {
      console.log(res, "获取健康管理关系");
      const list = res.data.data.filter(item =>
        familymemberid == item.familyMemberId
      )
      // 删除健康管理
      deleteHealthManage({
        id: list[0].healthManageId
      }).then(res => {
        console.log("删除健康管理", res);
        this.getInitData()
      })
    })

  },

  // 路由跳转
  skip() {
    const familyId = GETSTORAGE('familyId')
    updateFamilyArchiveStatus({
      familyId: familyId,
      status: "finish"
    }).then(res => {
      wx.navigateTo({
        url: '/pages/filing/accomplish/accomplish',
      })
    })

  },
  refresh() {
    this.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.msg && options.msg == 'refresh') {
      this.setData({
        btnFlag: false
      })
    } else {
      this.setData({
        btnFlag: true
      })
    }
    console.log(this.data.btnFlag);
    this.getUserInfo()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})